package com.sgb.kjwl.view.ui.fragment.material;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.MapView;
import com.amap.api.maps.model.Marker;
import com.swgk.core.util.LogUtil;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentListGoodsDistanceBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.kjwl.model.entity.user.PromoteGoodsEntity;
import com.sgb.link.event.LeaseEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.adapter.supplier3.PromoteGoodsAdapter;
import com.sgb.kjwl.view.ui.adapter.supplier3.SupplierRecommendAdapter;
import com.sgb.kjwl.view.widget.MapInfoDialog4;
import com.sgb.kjwl.view.widget.MapInfoWindow4;
import com.sgb.link.view.widget.PickCityPopWindow;
import com.sgb.kjwl.viewmodel.material.DistanceListModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

/**
 * 需求大厅tab页签数据列表页
 * 这需求
 */
@Deprecated
public class GoodsDiatanceListFragment extends AppFragment {

    private static final String DEMAND_TYPE = "demand_type";
    private  String goosType;
    private FragmentListGoodsDistanceBinding binding;
    @Inject
    DistanceListModel distanceListModel;
    private String searchName = "";
    private String tabName = "全部";
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    private String tabNames;

    private List<SupplierRecommendEntity> mapSupplierList = new ArrayList<>();

    private List<PickSelectEntity> distanceDatas = new ArrayList<>();
    private PickCityPopWindow pickDistancePopWindow;
    private HashMap conditionMap = new HashMap();
    private SupplierRecommendAdapter supplierRecommendAdapter;
    private PromoteGoodsAdapter promoteGoodsAdapter;
    private MapMarkerTools mapMarkerTools;

    private Double currentLat;
    private Double currentLong;

    private String TYPE_LIST = "列表";
    private String TYPE_MAP = "图查";

    private List<SupplierRecommendEntity> bundles = new ArrayList<>();

    public static GoodsDiatanceListFragment newInstance(String goodsType) {
        GoodsDiatanceListFragment fragment = new GoodsDiatanceListFragment();
        Bundle args = new Bundle();
        args.putString(DEMAND_TYPE, goodsType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                initdata();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
        goosType = getArguments().getString(DEMAND_TYPE);
        LogUtil.i("112", goosType);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_list_goods_distance, container, false);
        binding.setViewModel(distanceListModel);
        mapMarkerTools = new MapMarkerTools(getActivity(), getLifecycle());
        initMap(savedInstanceState);
        if (getArguments() != null) {
            goosType = getArguments().getString(DEMAND_TYPE);
            conditionMap.put("name", goosType);
        }
        return binding.getRoot();
    }

    private void initdata() {
        distanceListModel.getDistanceModel();
//        getdata();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initview();
        if (init && isVisible) {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            initdata();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseEvent event) {
//        if (event.getMessageTag() == EventConstant.EVENT_SERCHE_TAB) {
//            tabNames = (String) event.getMessageData();
//            conditionMap.put("name", goosType);
//            tabName = tabNames;
//            getdata("1");
//        }
//        //找供应商
//        if (event.getMessageTag() == EventConstant.EVENT_SERCHE_SUPPLIER) {
//            searchName = (String) event.getMessageData();
//            conditionMap.put("name", searchName);
//            tabName = tabNames;
//            getdata("1");
//        }
//        //找商品
//        if (event.getMessageTag() == EventConstant.EVENT_SERCHE_GOODS) {
//            searchName = (String) event.getMessageData();
//            conditionMap.put("item_cid1", "");
//            conditionMap.put("name", searchName);
//            tabName = tabNames;
//            getdata("2");
//        }
    }

    private void initview() {

        binding.tvLocation.setOnClickListener(this);
        binding.llDistance.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);
        binding.rightView.setOnClickListener(this);

        supplierRecommendAdapter = new SupplierRecommendAdapter(getActivity(), null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.demandList.setLayoutManager(layoutManager);

        binding.demandList.setAdapter(supplierRecommendAdapter);


        binding.demandList.setLoadingMoreEnabled(true);
        binding.demandList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getdata("1");
            }

            @Override
            public void onLoadMore() {
                conditionMap.put("latitude", currentLat);
                conditionMap.put("longitude", currentLong);
                Log.e("tagmapaddress", conditionMap.toString());
                distanceListModel.getSupplierListModel(conditionMap, true);
            }
        });

        supplierRecommendAdapter.setOnItemClick(new AdapterOnItemClick<SupplierRecommendEntity>() {
            @Override
            public void onItemClick(SupplierRecommendEntity supplierRecommendEntity, int position) {
                if (TextUtils.isEmpty(supplierRecommendEntity.getCompanyId())) {
                    ToastUtil.show(getContext(), "企业店铺id不能为空");
                    return;
                }
                ShopInfoForCompanyTradesActivity.startAct(getActivity(), supplierRecommendEntity.getCompanyId(), "", 0, 0);
            }
        });

        binding.demandList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.e("newstate:", newState + "");
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e("position:", layoutManager.findFirstVisibleItemPosition() + "");
                if (layoutManager.findFirstVisibleItemPosition() > 1) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });


        //距离
        pickDistancePopWindow = new PickCityPopWindow(getActivity());
//        pickDistancePopWindow.setBgView(binding.selectLayout);
        pickDistancePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                String distance = (String) key1;
                conditionMap.put("distance", distance);
                distanceListModel.getSupplierMapModel(conditionMap);
                distanceListModel.getSupplierListModel(conditionMap, false);
            }
        });

    }


    private void getdata(String type) {
        if ("1".equals(type)) {
            distanceListModel.getSupplierMapModel(conditionMap);
            distanceListModel.getSupplierListModel(conditionMap, false);
        } else {
//            distanceListModel.getGoodsMapModel(conditionMap);
            distanceListModel.getGoodsModel(conditionMap, false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_location://定位
                Intent intent = new Intent();
                intent.setClass(getActivity(), SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择定位地址");
                intent.putExtra(SelectAddressActivity.LATITUDE, currentLat);
                intent.putExtra(SelectAddressActivity.LONGTITUDE, currentLong);
                startActivityForResult(intent, 101);
                break;
            case R.id.ll_distance://距离选择
                showDistancePopWindow();
                if (distanceDatas == null) {
                    distanceListModel.getDistanceModel();
                }
                break;
            case R.id.img_back_top:
                binding.demandList.smoothScrollToPosition(0);
                break;

            case R.id.right_view:
                if (binding.rightView.getText().toString().equals(TYPE_MAP)) {
                    binding.rightView.setText(TYPE_LIST);
                    binding.demandList.setVisibility(View.GONE);
                    binding.mapView.setVisibility(View.VISIBLE);
                    binding.tvLocation.setVisibility(View.VISIBLE);
                    binding.vLine.setVisibility(View.VISIBLE);
                } else {
                    binding.rightView.setText(TYPE_MAP);
                    binding.demandList.setVisibility(View.VISIBLE);
                    binding.mapView.setVisibility(View.GONE);
                    binding.tvLocation.setVisibility(View.INVISIBLE);
                    binding.vLine.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }

    public void showGoodsList(List<PromoteGoodsEntity> datas, boolean isLoadMore) {
//        binding.demandList.setAdapter(null);
        binding.demandList.swapAdapter(promoteGoodsAdapter,true);
        if (isLoadMore) {
            binding.demandList.loadMoreComplete();
            if (datas.size() != 0) {
                promoteGoodsAdapter.addDatas(datas);
            }
        } else {
            binding.demandList.refreshComplete();
            if (datas.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.demandList.setLoadingMoreEnabled(false);
                binding.demandList.setVisibility(View.GONE);
            } else {
                binding.demandList.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                binding.demandList.setLoadingMoreEnabled(true);
            }
            promoteGoodsAdapter.setDatas(datas);
        }
    }


    public void showList(List<SupplierRecommendEntity> datas, boolean isLoadMore) {
//        binding.demandList.setAdapter(null);
        binding.demandList.setAdapter(supplierRecommendAdapter);
        if (isLoadMore) {
            binding.demandList.loadMoreComplete();
            if (datas.size() != 0) {
                supplierRecommendAdapter.addDatas(datas);
            }
        } else {
            binding.demandList.refreshComplete();
            if (datas.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.demandList.setLoadingMoreEnabled(false);
                binding.demandList.setVisibility(View.GONE);
            } else {
                binding.demandList.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                binding.demandList.setLoadingMoreEnabled(true);
            }
            supplierRecommendAdapter.setDatas(datas);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void showDistancePopWindow() {
        pickDistancePopWindow.showPopwindow(binding.selectLayout);
        pickDistancePopWindow.setData(distanceDatas);
    }

    public void showDistancePopWindow(List<DictEntity3> data) {
        setSecondDistanceDatas(data);
        if (data != null && data.size() > 0) {
            //未选择距离时设置一个最大默认距离
            conditionMap.put("distance", data.get(data.size() - 1).getId());
//            distanceListModel.getSupplierMapModel(conditionMap);
//            distanceListModel.getSupplierListModel(conditionMap, false);
        }
        pickDistancePopWindow.setData(distanceDatas);
    }

    private void setSecondDistanceDatas(List<DictEntity3> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (DictEntity3 entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }

        distanceDatas.clear();
        distanceDatas.addAll(types);
    }

    public void showMap(List<SupplierRecommendEntity> datas) {
        mapSupplierList = datas;
        addMarkInfoWindow(mapSupplierList);
    }

    private void addMarkInfoWindow(List<SupplierRecommendEntity> datas) {
        try {
            mapMarkerTools.mapClear();
            bundles.clear();
            for (int i = 0; i < datas.size(); i++) {
                if (null != datas && datas.size() > 0) {
                    SupplierRecommendEntity entity = datas.get(i);
                    if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                        double currentLat = Double.parseDouble(entity.getLatitude());
                        double currentLong = Double.parseDouble(entity.getLongitude());
                        if (currentLat == 0 || currentLong == 0) {
                            return;
                        }
                        mapMarkerTools.addPoiItem(currentLat, currentLong, "");
                        bundles.add(datas.get(i));
                    }
                }
            }
            mapMarkerTools.addAllMarkerToMap(R.mipmap.ic_map_overlay, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initMap(Bundle savedInstanceState) {
        MapView mMapView = binding.mapView;
        mapMarkerTools.init(savedInstanceState, mMapView);
        mapMarkerTools.setMarkerClick(new MapMarkerTools.MarkerClick() {
            @Override
            public void onMarkerClick(int pos, String title) {
                showMarkerView(pos, title);
            }

            @Override
            public void onMarkerClick(int pos, String title, Marker marker) {
            }

            @Override
            public void onLocationChanged(Double Lat, Double Log, String address) {
                if (currentLat == null || currentLat <= 0) {
                    currentLat = Lat;
                    currentLong = Log;
                    //设置经纬度以查询地图模式下的数据
                    conditionMap.put("latitude", currentLat);
                    conditionMap.put("longitude", currentLong);
                    distanceListModel.getSupplierListModel(conditionMap, false);
                    distanceListModel.getSupplierMapModel(conditionMap);
                    cameraToPosition();
                }
            }

            @Override
            public void getAddress(Double Lat, Double Log, String address) {

            }

            @Override
            public void failure() {
                distanceListModel.getSupplierListModel(conditionMap, false);
                distanceListModel.getSupplierMapModel(conditionMap);
            }
        });
    }

    //设置定位点
    private void cameraToPosition() {
        mapMarkerTools.setMyLocation(currentLat, currentLong);
    }


    private void showMarkerView(int pos, String title) {
        SupplierRecommendEntity entity = bundles.get(pos);
        MapInfoWindow4 mapInfoWindow = new MapInfoWindow4(getActivity());
        mapInfoWindow.setData(entity);

        new MapInfoDialog4(getActivity(), null)
                .setDialogClickCallBack(new MapInfoDialog4.DialogClickCallBack() {
                    @Override
                    public void onClickShop(String shopId) {
                        if (TextUtils.isEmpty(shopId)) {
                            ToastUtil.show(getContext(), "企业店铺id不能为空");
                            return;
                        }
                        ShopInfoForCompanyTradesActivity.startAct(getActivity(), shopId, "", 0, 0);
                    }
                })
                .setData(mapInfoWindow.getData()).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            currentLat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            currentLong = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);
            distanceListModel.getSupplierListModel(conditionMap, false);

            //设置经纬度以查询地图模式下的数据
            distanceListModel.getSupplierMapModel(conditionMap);

            cameraToPosition();
        }
    }

}
